package com.arsn.myf.security.controller;
import com.arsn.myf.common.annotation.ApiLog;
import com.arsn.myf.common.util.auth.AuthUtil;
import com.arsn.myf.common.util.result.R;
import com.arsn.myf.common.util.spring.SpringUtils;
import com.arsn.myf.security.entity.UserInfo;
import com.arsn.myf.security.service.TokenService;
import com.arsn.myf.system.entity.User;
import com.arsn.myf.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.*;

/**
 * 登录
 * @author zhongrj
 * @since 2022-06-16
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户登录", tags = "用户登录")
public class LoginController {

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    /**
     * 自定义登录
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @ApiLog("登录")
    @PostMapping("/login")
    @ApiOperation(value = "自定义登录")
    public R login(String username, String password){
        // 用户验证 authenticate方法会去调用自定义 myAuthenticationProvider 进行自定义校验
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        //取出用户登录信息
        UserInfo userInfo = (UserInfo) authentication.getPrincipal();
        //定义返回 map
        Map<String, Object> map = new HashMap<>();
        //创建token
        map.put("token",tokenService.createToken(userInfo));
        //返回
        return R.data(map);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息")
    public R getUserInfo(){
        // 获取用户信息
        User user = AuthUtil.getUser().getUser();
        // 查询角色集合
        Set<String> roles = userService.getRolePermission(user);
        // 查询权限集合
        Set<String> permissions = userService.getMenuPermission(user);
        Map<String,Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permission", permissions);
        map.put("env", SpringUtils.getActiveProfile());
        //返回
        return R.data(map);
    }
}
